<template>
  <el-dialog
    v-model="isShow"
    title="新增"
    width="680px"
    :before-close="handleClose"
  >
    <div>
      <el-form
        ref="formRef"
        :rules="rules"
        :model="formDate"
        label-width="120px"
        class="demo-formDate"
      >
        <el-form-item label="任务名：" prop="taskName">
          <el-input
            v-model.trim="formDate.taskName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型：" prop="intervalType">
          <el-radio-group v-model="formDate.intervalType">
            <el-radio :label="FREQUENCY.ONCE">单次</el-radio>
            <el-radio :label="FREQUENCY.MULTIPLE">循环</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="formDate.intervalType === FREQUENCY.MULTIPLE">
          <el-form-item label="策略：" prop="cronType">
            <el-radio-group v-model="formDate.cronType">
              <el-radio :label="MODE_TYPE.WEEK">按周</el-radio>
              <el-radio :label="MODE_TYPE.DATA">按日期</el-radio>
              <el-radio :label="MODE_TYPE.DAYS">每天</el-radio>
              <el-radio :label="MODE_TYPE.EXPRESSION">表达式</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="MODE_TYPE.WEEK === formDate.cronType"
            label="星期："
            prop="cronWeekday"
          >
            <el-checkbox-group v-model="formDate.cronWeekday">
              <el-checkbox
                v-for="(item, key) in WEEKS"
                :key="item"
                :label="item"
                name="cronWeekday"
                >周{{ key }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
          <el-form-item
            v-if="MODE_TYPE.DATA === formDate.cronType"
            label="日期："
            required
          >
            <el-row>
              <el-col :span="8">
                <el-form-item prop="cronMonth">
                  <el-select
                    :style="{ width: '120px' }"
                    v-model="formDate.cronMonth"
                    placeholder="请选择月份"
                    @change="handleChangeMoth"
                  >
                    <el-option
                      v-for="(item, index) in 12"
                      :label="index + 1"
                      :value="index"
                      :key="index"
                    />
                  </el-select>
                  月
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="cronDay">
                  <el-select
                    :style="{ width: '120px' }"
                    v-model="formDate.cronDay"
                    placeholder="请选择日"
                  >
                    <el-option
                      v-for="(item, index) in curDays"
                      :label="index + 1"
                      :value="index + 1"
                      :key="index"
                    />
                  </el-select>
                  日
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item
            v-if="formDate.cronType === MODE_TYPE.EXPRESSION"
            label="表达式："
            prop="cronExpression"
          >
            <el-input
              v-model.trim="formDate.cronExpression"
              placeholder="请输入表达式"
            ></el-input>
          </el-form-item>
        </div>
        <el-form-item
          v-if="formDate.intervalType === FREQUENCY.ONCE"
          label="执行时间："
          prop="exeDate"
        >
          <el-date-picker
            v-model="formDate.exeDate"
            type="datetime"
            placeholder="请选择"
          ></el-date-picker>
        </el-form-item>
        <el-form-item v-if="getShowExeDate()" label="执行时间：" prop="exeTime">
          <el-time-picker
            v-model="formDate.exeTime"
            placeholder="请选择"
          ></el-time-picker>
        </el-form-item>
        <el-form-item label="任务开始时间：" prop="startTime">
          <el-date-picker
            v-model="formDate.startTime"
            type="datetime"
            placeholder="请选择"
          ></el-date-picker>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  defineProps,
  ref,
  reactive,
  defineEmits,
  nextTick,
  watch,
  computed
} from "vue";
import { ElTimePicker } from "element-plus";
import days from "dayjs";

import NotifMessage from "/@/utils/message/notification";
import { postAddRepeat } from "/@/api/flowProgress";
import { FREQUENCY, WEEKS, MODE_TYPE } from "../detail/types";

const rules = {
  taskName: { required: true, message: "请输入任务名称", trigger: "blur" },
  intervalType: { required: true, message: "请选择类型", trigger: "change" },
  cronType: { required: true, message: "请选择策略", trigger: "change" },
  cronWeekday: { required: true, message: "请选择星期", trigger: "change" },
  cronMonth: { required: true, message: "请选择月份", trigger: "change" },
  cronDay: { required: true, message: "请选择日", trigger: "change" },
  cronExpression: {
    required: true,
    message: "请选择输入表达式",
    trigger: "blur"
  },
  exeDate: { required: true, message: "请选择执行时间", trigger: "change" },
  exeTime: { required: true, message: "请选择执行时间", trigger: "change" },
  startTime: {
    required: true,
    message: "请选择任务开始时间",
    trigger: "change"
  }
};

const initData = {
  taskName: "",
  intervalType: "1",
  cronType: "",
  cronWeekday: [],
  cronMonth: "",
  cronDay: "",
  cronExpression: "",
  exeDate: "", // 执行时间格式 2021-12-12 00:00:00
  exeTime: "", // 执行时间格式 00:00:00
  startTime: ""
};

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  projectProgressId: {
    type: String
  },
  onClose: {
    type: Function
  }
});

const emit = defineEmits<{
  (e: "onClose"): void;
}>();

watch(
  () => props.visible,
  () => {
    if (props.visible) {
      nextTick(() => {
        Object.assign(formDate, initData);
        formRef.value.resetFields();
      });
    }
  }
);

const isShow = computed(() => props.visible || false);

const formDate = reactive({ ...initData });

const formRef = ref<HTMLFormElement | null>(null) as any;
const curDays = ref(0);

const getShowExeDate = () =>
  [MODE_TYPE.WEEK, MODE_TYPE.DATA, MODE_TYPE.DAYS].includes(
    formDate.cronType
  ) && formDate.intervalType === FREQUENCY.MULTIPLE;

const handleChangeMoth = e => {
  curDays.value = days().month(e).daysInMonth();
};

const handleClose = () => {
  Object.assign(formDate, initData);
  formRef.value.resetFields();
  nextTick(() => {
    emit("onClose");
  });
};

const handleSave = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      const params = {
        projectProgressId: props.projectProgressId,
        taskName: formDate.taskName,
        quartzDto: {
          startTime: days(formDate.startTime).format("YYYY-MM-DD HH:mm:ss"),
          intervalType: formDate.intervalType
        }
      };
      // 单次
      if (formDate.intervalType === FREQUENCY.ONCE) {
        params.quartzDto["exeDate"] = days(formDate.exeDate).format(
          "YYYY-MM-DD HH:mm:ss"
        );

        if (formDate.exeDate <= formDate.startTime) {
          NotifMessage.error("执行时间必须大于任务开始时间");
          return;
        }
      }
      // 循环
      if (formDate.intervalType === FREQUENCY.MULTIPLE) {
        params.quartzDto["cronType"] = formDate.cronType;
        if (formDate.cronType === MODE_TYPE.WEEK) {
          // 策略 => 按周
          params.quartzDto["cronWeekday"] = formDate.cronWeekday;
          params.quartzDto["cronHour"] = days(formDate.exeTime).format("HH");
          params.quartzDto["cronMinute"] = days(formDate.exeTime).format("mm");
        }
        if (formDate.cronType === MODE_TYPE.DATA) {
          // 策略 => 日期
          params.quartzDto["cronMonth"] = formDate.cronMonth + 1;
          params.quartzDto["cronDay"] = formDate.cronDay;
          params.quartzDto["cronHour"] = days(formDate.exeTime).format("HH");
          params.quartzDto["cronMinute"] = days(formDate.exeTime).format("mm");
        }
        if (formDate.cronType === MODE_TYPE.DAYS) {
          // 策略 => 每天
          params.quartzDto["cronHour"] = days(formDate.exeTime).format("HH");
          params.quartzDto["cronMinute"] = days(formDate.exeTime).format("mm");
        }
        if (formDate.cronType === MODE_TYPE.EXPRESSION) {
          // 策略 => 表达式
          params.quartzDto["cronExpression"] = formDate.cronExpression;
        }
      }
      const { code, message } = await postAddRepeat(params);
      if (code === 200) {
        handleClose();
        NotifMessage.success("创建成功");
      } else {
        NotifMessage.error(message);
      }
    } else {
      return false;
    }
  });
};
</script>
